<template>
  <div class="DigitalCollationAdd">
    <div class="form-card">
      <div class="card-title">数字著录</div>
      <div class="card-line"></div>
      <div class="card-steps">
        <ApproveProcess code="A0578" />
      </div>
      <!-- <div class="card-tip">
        <img
          src="@/assets/images/meeting_add_tip.png"
          alt=""
        />
        <span>
          {{ hint }}
        </span>
      </div> -->
      <div class="form-content">
        <NScrollbar>
          <NSpin :show="false">
            <n-form
              ref="formRef"
              :model="formModel"
              :rules="rules"
              label-placement="left"
              label-width="auto"
              require-mark-placement="right-hanging"
              class="form-container"
            >
              <n-grid
                :cols="2"
                :x-gap="24"
              >
                <n-grid-item>
                  <n-form-item
                    label="类型"
                    path="type"
                  >
                    <n-select
                      v-model:value="formModel.type"
                      :options="typeOptions"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="著作类型"
                    path="workType"
                  >
                    <div
                      class="type-name"
                      @click="handletype"
                    >
                      {{ formModel.fileCount ? formModel.fileCount : '选择格式' }}
                    </div>
                  </n-form-item>
                </n-grid-item>
              </n-grid>
              <div class="form-line"></div>
              <n-grid
                :cols="2"
                :x-gap="24"
              >
                <n-grid-item>
                  <n-form-item
                    label="著录识别号/条码号"
                    path="identificationNumber"
                  >
                    <n-input v-model:value="formModel.identificationNumber" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="主题词"
                    path="subject"
                  >
                    <n-input v-model:value="formModel.subject" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="版本名称"
                    path="callNumber"
                  >
                    <n-input v-model:value="formModel.callNumber" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="计算机文件名"
                    path="fileName"
                  >
                    <n-input v-model:value="formModel.fileName" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="中华版本收藏主体名称"
                    path="collectionName"
                  >
                    <n-input v-model:value="formModel.collectionName" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="中华版本收藏主体编码"
                    path="collectionCode"
                  >
                    <n-input v-model:value="formModel.collectionCode" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="原始载体"
                    path="originalCode"
                  >
                    <n-input v-model:value="formModel.originalCode" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="保管期限"
                    path="retentionPeriod"
                  >
                    <n-date-picker
                      v-model:value="formModel.retentionPeriod"
                      type="date"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="密级"
                    path="securityLevel"
                  >
                    <n-select
                      v-model:value="formModel.securityLevel"
                      :options="securityLevelOptions"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="来源"
                    path="year"
                  >
                    <n-input v-model:value="formModel.year" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="计算机文件大小"
                    path="fileSize"
                  >
                    <n-input-number v-model:value="formModel.fileSize" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="著录者"
                    path="cataloger"
                  >
                    <n-input v-model:value="formModel.cataloger" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="格式名称"
                    path="fileCount"
                  >
                    <n-select
                      v-model:value="formModel.workType"
                      :options="workTypeOptions"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="存储地址"
                    path="storageLocation"
                  >
                    <n-input v-model:value="formModel.storageLocation" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="文件数量"
                    path="fileCount"
                  >
                    <n-input v-model:value="formModel.fileCount" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item style="width: 1px">
                  <!-- <n-form-item
                    label="格式名称"
                    path="fileCount"
                  >
                    <n-input v-model:value="formModel.fileCount" />
                  </n-form-item> -->
                </n-grid-item>
                <n-grid-item>
                  <n-form-item
                    label="内容描述"
                    path="description"
                  >
                    <n-input
                      v-model:value="formModel.description"
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 5 }"
                    />
                  </n-form-item>
                </n-grid-item>

                <n-grid-item>
                  <n-form-item
                    label="备注"
                    path="remarks"
                  >
                    <n-input
                      v-model:value="formModel.remarks"
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 5 }"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="预览图">
                    <n-upload
                      list-type="image-card"
                      :max="1"
                      :custom-request="(e: any) => commonUpload(e)"
                      :on-remove="handleRemove"
                      :default-file-list="tasmpList"
                      directory-dnd
                    >
                      <n-upload-dragger>
                        <div class="upload-container">
                          <n-icon
                            size="41"
                            :depth="3"
                          >
                            <CloudUpload />
                          </n-icon>
                          <n-text style="font-size: 12px; color: #326c53">
                            点击或将文件拖拽到这上传
                          </n-text>
                        </div>
                      </n-upload-dragger>
                    </n-upload>
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </n-form>
          </NSpin>
        </NScrollbar>
      </div>
    </div>
    <div class="form-bottom">
      <div class="btn-list">
        <n-button @click="handleReset">取消</n-button>
        <n-button @click="handleSubmit">暂存</n-button>
        <n-button
          type="primary"
          @click="handleSubmit"
        >
          确定
        </n-button>
      </div>
    </div>
    <NModal
      :auto-focus="false"
      v-model:show="typeModalVisiable"
    >
      <div class="custom-modal type-modal">
        <div class="modal-title">
          <span>请选择类型</span>
          <img
            src="@/assets/images/meeting_dialog_close.png"
            alt=""
            @click="typeModalVisiable = false"
          />
        </div>
        <div class="modal-container">
          <div class="type-list">
            <div
              class="type-item"
              v-for="(item, index) in typeList"
              :key="item.value"
              :style="{
                backgroundImage: `url(${getAssetUrl(`DigitalCollation/type${index + 1}.png`)})`
              }"
              @click="handletypeClick(item)"
            >
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </NModal>
    <NModal
      :auto-focus="false"
      v-model:show="matterModalVisiable"
    >
      <div class="custom-modal matter-modal">
        <div class="modal-title">
          <span>请选择关联实物</span>
          <img
            src="@/assets/images/meeting_dialog_close.png"
            alt=""
            @click="matterModalVisiable = false"
          />
        </div>
        <div class="modal-container">
          <div class="matter-list">
            <div
              class="matter-item"
              v-for="(item, index) in matterList"
              :key="item.value"
              @click="handleMatterClick(item)"
            >
              <img
                :src="getAssetUrl(`DigitalCollation/matter${index + 1}.png`)"
                alt=""
              />
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </NModal>
    <IncludedModal
      v-model:show="includedModalVisible"
      @select="handleIncludedSelect"
      @reset="handleIncludedReset"
      @cancel="handleIncludedCancel"
      @submit="handleIncludedSubmit"
    />
    <NotIncludedModal
      v-model:show="notIncludedModalVisible"
      @select="handleNotIncludedSelect"
      @reset="handleNotIncludedReset"
      @cancel="handleNotIncludedCancel"
      @submit="handleNotIncludedSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, onUpdated, onBeforeUpdate, watch } from 'vue'
import {
  useMessage,
  NScrollbar,
  type FormRules,
  type UploadCustomRequestOptions,
  NUploadDragger
} from 'naive-ui'
import IncludedModal from './components/IncludedModal.vue'
import NotIncludedModal from './components/NotIncludedModal.vue'

import dayjs from 'dayjs'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { getAssetUrl } from '@/utils/common'
import ApproveProcess from '@/components/Approve/approveProcess.vue'
import { useTagStore } from '@/stores/layout'
import { CloudUpload } from '@vicons/ionicons5'
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NDatePicker,
  NUpload,
  NButton,
  NSpace,
  NGrid,
  NGridItem,
  NSpin,
  NIcon,
  NModal
} from 'naive-ui'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const formRef1 = ref(null)
const message = useMessage()
const formModel = ref({
  type: null,
  workType: null,
  identificationNumber: '',
  subject: '',
  callNumber: '',
  fileName: '',
  collectionName: '',
  collectionCode: '',
  originalCode: '',
  retentionPeriod: null,
  securityLevel: null,
  year: '',
  fileSize: null,
  cataloger: '',
  fileCount: '',
  storageLocation: '',
  description: '',
  remarks: ''
})

const rules = ref<FormRules>({
  type: {
    required: true,
    message: '请选择类型',
    trigger: ['blur', 'change']
  },
  workType: {
    required: true,
    message: '请选择著作类型',
    trigger: ['blur', 'change']
  },
  identificationNumber: {
    required: true,
    message: '请输入著录识别号/条码号',
    trigger: ['blur', 'input']
  },
  subject: {
    required: true,
    message: '请输入主题词',
    trigger: ['blur', 'input']
  },
  callNumber: {
    required: true,
    message: '请输入馆藏书号',
    trigger: ['blur', 'input']
  },
  fileName: {
    required: true,
    message: '请输入计算机文件名',
    trigger: ['blur', 'input']
  },
  collectionName: {
    required: true,
    message: '请输入中华版本收藏主体名称',
    trigger: ['blur', 'input']
  },
  collectionCode: {
    required: true,
    message: '请输入中华版本收藏主体编码',
    trigger: ['blur', 'input']
  },
  originalCode: {
    required: true,
    message: '请输入原始编码',
    trigger: ['blur', 'input']
  },
  retentionPeriod: {
    required: true,
    type: 'number',
    message: '请选择保管期限',
    trigger: ['blur', 'change']
  },
  securityLevel: {
    required: true,
    message: '请选择密级',
    trigger: ['blur', 'change']
  },
  year: {
    required: true,
    message: '请输入年款',
    trigger: ['blur', 'input']
  },
  fileSize: {
    required: true,
    type: 'number',
    message: '请输入计算机文件大小',
    trigger: ['blur', 'change']
  },
  cataloger: {
    required: true,
    message: '请输入著录者',
    trigger: ['blur', 'input']
  },
  fileCount: {
    required: true,
    message: '请输入格式名称',
    trigger: ['blur', 'input']
  },
  storageLocation: {
    required: true,
    message: '请输入存储地址',
    trigger: ['blur', 'input']
  },
  description: {
    required: true,
    message: '请输入内容描述',
    trigger: ['blur', 'input']
  },
  remarks: {
    required: false, // 备注可以是可选的
    message: '请输入备注',
    trigger: ['blur', 'input']
  }
})

const getFormItemsByType = (type: string) => {
  const commonItems = [
    'identificationNumber',
    'subject',
    'callNumber',
    'collectionName',
    'collectionCode',
    'originalCode',
    'retentionPeriod',
    'securityLevel',
    'cataloger',
    'storageLocation',
    'description',
    'remarks'
  ]

  switch (type) {
    case '文本':
      return [...commonItems, 'fileName', 'fileSize', 'fileCount']
    case '图像':
      return [...commonItems, 'fileName', 'fileSize', 'fileCount', 'captureDevice']
    case '音频':
      return [...commonItems, 'fileName', 'fileSize', 'duration', 'captureDevice']
    case '视频':
      return [...commonItems, 'fileName', 'fileSize', 'duration', 'captureDevice']
    case '其他':
      return [...commonItems, 'fileName', 'fileSize', 'fileCount']
    default:
      return commonItems
  }
}

const typeOptions = ref([
  {
    label: '实物版本',
    value: 'type1'
  },
  {
    label: '虚拟版本',
    value: 'type2'
  },
  {
    label: '数字档案',
    value: 'type3'
  }
])

const workTypeOptions = [{ label: '请选择', value: null }]
const securityLevelOptions = [{ label: '请选择', value: null }]

const typeModalVisiable = ref(false)
const handletype = () => {
  typeModalVisiable.value = true
}

const typeList = ref([
  {
    label: '文本',
    value: 'type1'
  },
  {
    label: '音频',
    value: 'type2'
  },
  {
    label: '图像',
    value: 'type3'
  },
  {
    label: '视频',
    value: 'type4'
  },
  {
    label: '其他',
    value: 'type5'
  }
])
const handletypeClick = (e: any) => {
  formModel.value.fileCount = e.label
  typeModalVisiable.value = false
}

const matterModalVisiable = ref(false)
const matterList = ref([
  {
    label: '以入藏藏品',
    value: 'matter1'
  },
  {
    label: '未入藏藏品',
    value: 'matter2'
  }
])
const handleMatterClick = (e: any) => {
  matterModalVisiable.value = false
  if (e.value === 'matter1') {
    includedModalVisible.value = true
  } else if (e.value === 'matter2') {
    notIncludedModalVisible.value = true
  }
}

const includedModalVisible = ref(false)

const handleIncludedSelect = (formData: any) => {
  // 处理查询逻辑
}

const handleIncludedReset = () => {
  // 处理重置逻辑
}

const handleIncludedCancel = () => {
  // 处理取消逻辑
}

const handleIncludedSubmit = (formData: any) => {
  // 处理提交逻辑
  router.push({
    path: '/OA/DigitalCollation/DigitalCollections'
  })
}

const notIncludedModalVisible = ref(false)

const handleNotIncludedSelect = (formData: any) => {
  // 处理查询逻辑
}

const handleNotIncludedReset = () => {
  // 处理重置逻辑
}

const handleNotIncludedCancel = () => {
  // 处理取消逻辑
}

const handleNotIncludedSubmit = (formData: any) => {
  // 处理提交逻辑
  router.push({
    path: '/OA/DigitalCollation/DigitalCollections'
  })
}

const imgHZ = ['jpg', 'png', 'jpeg']
const tasmpList = ref<any>([])
const commonUpload = async ({
  file,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  const tmp = file.name.split('.')
  if (!imgHZ.includes(tmp[tmp.length - 1])) return message.error('请上传图片类型'), onError()
  const fileData = new FormData()
  fileData.append('file', file.file as File)
  const [error, res] = await sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: fileData,
      onUploadProgress(v: any) {
        onProgress({ percent: Math.ceil(v.progress) })
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error('上传失败'), onError()
  tasmpList.value.push({
    id: res.data.fileId,
    name: res.data.name,
    status: 'finished',
    url: res.data.url
  })
  message.success('上传成功')
  // returnPictures()
  onFinish()
}

// 删除
const handleRemove = ({ file }: any) => {
  const index = tasmpList.value.findIndex((it: any) => it.name == file.name)
  tasmpList.value.splice(index, 1)
  message.success('删除成功')
  // returnPictures()
  return true
}

watch(
  () => tasmpList.value,
  () => {
    formData.value.image = tasmpList.value[0]?.url
  },
  {
    deep: true
  }
)
const handleSubmit = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      message.success('表单提交成功')
      matterModalVisiable.value = true
      // 这里可以添加提交表单的逻辑
    } else {
      message.error('请填写所有必填字段')
      matterModalVisiable.value = true
    }
  })
}
// const handleReset = () => {
//   formModel.value = {
//     type: null,
//     workType: null,
//     identificationNumber: '',
//     subject: '',
//     callNumber: '',
//     fileName: '',
//     collectionName: '',
//     collectionCode: '',
//     originalCode: '',
//     retentionPeriod: null,
//     securityLevel: null,
//     year: '',
//     fileSize: null,
//     cataloger: '',
//     fileCount: '',
//     storageLocation: '',
//     description: '',
//     remarks: ''
//   }
// }

const handleReset = () => {
  router.back() // 返回上一页
}

onMounted(async () => {
  //   getWorkFlow()
})
watch(
  () => route.path,
  async () => {
    formModel.value.type = route.query.type
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.DigitalCollationAdd {
  position: relative;
  width: 100%;
  height: 100%;
}
.form-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 20px;
  background: #e1e1e1;
  .card-title {
    display: flex;
    align-items: center;
    width: 100%;
    height: 34px;
    color: #1d2129;
    font-size: 24px;
    font-weight: 500;
    line-height: 34px;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 7px;
      border-radius: 2.5px;
      background: #6cb187;
    }
  }
  .card-line {
    width: 100%;
    height: 1px;
    margin-top: 16px;
    background-color: #fff;
  }
  .card-steps {
    width: 100%;
    // display: flex;
    // justify-content: flex-start;
    margin: 20px;
    // margin-left: 200px;
  }
  .card-tip {
    display: flex;
    width: 880px;
    margin: 20px 0;
    padding: 4px 8px;
    justify-content: center;
    align-items: center;
    gap: 8px;
    border-radius: 8px;
    background: #f3f8f2;
    color: #4e5969;
    font-size: 14px;
    line-height: 34px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    img {
      width: 16px;
      height: 16px;
    }
    span {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .form-content {
    display: flex;
    justify-content: center;
    width: 100%;
    height: calc(100% - 95px);
    padding-top: 41px;
    .form-container {
      padding: 0 100px;
      .form-line {
        width: 100%;
        height: 0px;
        margin-bottom: 24px;
        border-top: 1px dashed #f1f2f4;
      }
      .type-name {
        display: flex;
        width: 102px;
        height: 32px;
        padding: 0px 12px;
        justify-content: center;
        align-items: center;
        border-radius: 2px;
        border: 1px solid #0b8d61;
        background: #fff;
        color: #0b8d61;
        font-size: 12px;
        line-height: 22px;
        cursor: pointer;
      }
      .upload-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
        width: 100%;
        height: 100%;
        padding: 4px 4px;
      }
    }
  }
}
.form-bottom {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 55px;
  border-top: 1px solid #f7f8f9;
  //   background: #f0efee;
  background: #ffffff;
  z-index: 999;
  .btn-list {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
    width: 100%;
    height: 100%;
    padding-right: 20px;
  }
}
.type-modal {
  width: 1252px;
  height: 395px;
  .type-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .type-item {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 16px;
      width: 208.1px;
      height: 107px;
      // border: 1px solid #00895b;
      cursor: pointer;
      background-size: cover;
      background-repeat: no-repeat;
      &:hover {
      }
      img {
        width: 100%;
        height: 100%;
      }
      span {
        color: #1d2129;
        font-size: 24px;
        font-weight: 600;
      }
    }
  }
}
.matter-modal {
  width: 480px;
  height: 240px;
  .matter-list {
    display: flex;
    gap: 76px;
    .matter-item {
      display: inline-flex;
      padding: 8px 17px;
      justify-content: center;
      align-items: center;
      gap: 8px;
      border-radius: 2px;
      border: 1px solid #326c53;
      background: rgba(66, 143, 110, 0.28);
      color: #326c53;
      font-size: 14px;
      line-height: 24px; /* 171.429% */
      cursor: pointer;
      img {
        width: 24px;
        height: 24px;
      }
    }
  }
}
:deep(.n-form-item) {
  //   width: 500px;
}
:deep(.n-form-item-blank) {
  width: 328px;
}
:deep(.n-upload-trigger--image-card) {
  display: flex;
  width: 160px;
  height: 90px;
  justify-content: space-between;
  align-items: center;
}
</style>
